import React from 'react';
import { Card, Descriptions, Button, Popconfirm, Select, Row, Col } from 'antd';
import SearchTable from '@/components/common/SearchTable';
import { getDicByKey, getDictOptionsByCode } from '@/support/common';
import { connect } from 'dva';
import moment from 'moment';
import style from './tboxTab.less';
import PropTypes from 'prop-types';

const statusList = [
  { value: 0, label: '获取中' },
  { value: 1, label: '获取失败' },
  { value: 2, label: '获取成功' },
];

@connect((state: any) => ({
  vehicleInfoQuery: state.vehicleInfoQuery,
  loading: state.loading.effects['vehicleInfoQuery/getDataWithRes'],
  menu: state.menu,
}))
export default class TboxTab extends React.Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      data: {
        deviceId: '',
        deviceName: '',
        deviceStatus: '',
        versionHardware: '',
        createDate: '',
        versionSoftware: '',
        batchNo: '',
        imei: '',
        ssid: '',
        pin: '',
        locBluetoothIds: '',
        dynamicSecretkey: '',
        deviceSkey: '',
        bluetoothMac: '',
        bluetoothId: '',
        bluetoothName: '',
        eolDate: '',
        aesKey: '',
        atbType: '',
        productReference: '',
        apnFlag: '',
        atbSn: '',
      },
      current: 'history',
      statusNum: 0,
      logType: '',
    };
  }
  onSource = (page, size, args) =>
    new Promise(async resolve => {
      const { vehicleInfoQuery } = this.props;
      const res = await this.props.dispatch({
        type: 'vehicleInfoQuery/getFetchPage',
        payload: {
          url: '/ipda/findreplacehistory',
          // vin: 'LGJETESTCAOLU0001',
          vin: vehicleInfoQuery.vin,
          current: page,
          pageSize: size,
          deviceType: 2,
          ...args,
        },
      });
      if (res && res.statusCode === '0') {
        resolve({
          total: res.data.pagination.total,
          data: res.data.list,
        });
      } else {
        resolve({
          total: 0,
          data: [],
        });
      }
    });
  getTBoxList = async (page, size, args) => {
    const {logType}=this.state;
    const { vehicleInfoQuery, dispatch } = this.props;
    const [start, end] = args?.time || [];
    const startTime = start ? moment(start).startOf('date').valueOf() : undefined;
    const endTime = end ? moment(end).endOf('date').valueOf() : undefined;
    const logTypeMask = logType || undefined;
    const res = await dispatch({
      type: 'vehicleInfoQuery/postFetchPage',
      payload: {
          url: '/log/upload/tboxLogList',
        // url: '/ipda/findreplacehistory',
        vin: vehicleInfoQuery.vin,
        pageNo: page,
        pageSize: size,
        status: args?.status,
        startTime,
        endTime,
        logTypeMask,
      },
    });
    //   console.log(res);
    // const {statusCode,data} = res || {}
    const { statusCode, data } = res || {};

    if (statusCode === '0') {
      return {
        total: data?.pagination?.total || 0,
        data: data?.list,
      };
    }
    return {
      total: 0,
      data: [
        // { sid: 1, status: 1 },
        // { sid: 2, status: 2 },
      ],
    };
  };
  getStatusFn = () => {
    let statusNum = 15;
    this.setState({
      statusNum,
    });
    const {logType}=this.state;
    const { vehicleInfoQuery, dispatch } = this.props;
    if (!this?.state?.statusNum) {
      dispatch({
        type: 'vehicleInfoQuery/postData',
        payload: {
            url: '/log/upload/uploadRequest',
        //   url: '/ipda/findreplacehistory',
          vin: vehicleInfoQuery.vin,
          logTypeMask: logType,
        },
      });
    }

    const fn = setInterval(() => {
      statusNum--;
      this.setState({
        statusNum,
      });
      if (statusNum === 0) {
        clearInterval(fn);
        // 数据请求
        // this.getTBoxList()
        this?.searchRef?.submit();
      }
    }, 1000);
  };
  static contextTypes = {
    dicData: PropTypes.any,
  };

  componentDidMount() {
    this.getDetail();
  }
  componentWillUnmount = () => {
    this.setState = (state, callback) => {
      return;
    };
  };
  getDetail() {
    const { vehicleInfoQuery } = this.props;
    const { dispatch } = this.props;

    vehicleInfoQuery.tbox
      ? dispatch({
          type: 'vehicleInfoQuery/getDataWithRes',
          payload: {
            url: '/basedata/findtboxdetail',
            deviceId: vehicleInfoQuery.tbox,
          },
          callback: response => {
            if (response && response.statusCode == '0' && response.data) {
              this.setState({
                data: Object.assign(this.state.data, response.data),
              });
            }
          },
        })
      : '';
  };
  onTypeChange =(val:any)=>{
    this.setState({
      logType: val
    })
  }
  resetLogType = ()=>{
    this.setState({
      logType: ''
    })
  }
  render() {
    const { context } = this;
    const { data, current, statusNum } = this.state;
    const { loading } = this.props;
    const {
      vehicleInfoQuery: {
        pageData: { pagination },
      },
    } = this.props;
    const logTypeMask = getDictOptionsByCode(this.context.dicData, 'logTypeMask');
    const { menu: { permissions }} = this.props;
    const isAuth = permissions.includes('/connectPlat/vehicleInfoQuery/vehicleInfoQueryDetail/vehicleInfoQueryDetail_logType');
    const customStyle = isAuth ? '' : 24;
    const columns = [
      {
        title: '序号',
        dataIndex: 'index',
        render: (text: any, record: any, index: any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        },
      },
      {
        title: '换件时间',
        dataIndex: 'createDate',
        render: (text: any, record: any, index: any) => {
          return text && moment(text).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '原TBOX编号',
        dataIndex: 'oldDeviceId',
      },
      {
        title: '原一体机编号',
        dataIndex: 'oldAtbSn',
      },
      {
        title: '新TBOX编号',
        dataIndex: 'newDeviceId',
      },
      {
        title: '新一体机编号',
        dataIndex: 'newAtbSn',
      },
    ];
    const TBoxColumns = [
      {
        title: '序号',
        dataIndex: 'index',
        render: (text: any, record: any, index: any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        },
      },
      {
        title: '获取时间',
        dataIndex: 'getTime',
        render:(val:any)=>{
            return  moment(val).format('YYYY-MM-DD HH:mm:ss')
        }
      },
      {
        title: '获取状态',
        dataIndex: 'status',
        render(text: number) {
          return statusList.find(e => `${e?.value}` === text)?.label;
        },
      },
      {
        title: '日志状态',
        dataIndex: 'logTypeMask',
        render:(text: any)=> {
          if (text == null) {
            return '';
          }
          return getDicByKey(this.context.dicData, `logTypeMask`, text + '');
        },
      },
      {
        title: '操作区',
        dataIndex: '操作',
        render: (text: any, record: any) => {
          const fn = (strUrl: any, name: any) => {
            const url = record?.file_uri;
            window.location.href = url;

            // const aLink = document.createElement('a');
            // document.body.appendChild(aLink);
            // aLink.style.display = 'none';
            // aLink.href = url
            // // aLink.download = name;
            // aLink.click();
            // document.body.removeChild(aLink);
          };

          return record?.status == 2 ? (
            <Popconfirm key="下载" title="是否确认下载" onConfirm={fn}>
              <Button type="primary" ghost>
                下载
              </Button>
            </Popconfirm>
          ) : (
            <Button type="primary" ghost disabled={true}>
              下载
            </Button>
          );
        },
      },
    ];

    const searchItems = [
      {
        title: '发送时间',
        type: 'rangePicker',
        key: 'time',
        showTime:false,
        format:"YYYY-MM-DD",
        // initialValue: ['', ''],
        customStyle: 8,
      },
      {
        title: '获取状态',
        type: 'select',
        key: 'status',
        selectOptions: statusList,
        customStyle: 8,
        initialValue: `${statusList[0]?.value}`,
        allowClear: false,
      },
    ];

    const tabList = [
      {
        tab: '换件历史记录',
        key: 'history',
        render: () => (
          <>
            <SearchTable
              tableProps={{
                rowKey: 'sid',
                scroll: { x: 'max-content' },
                columns: columns,
                onSource: this.onSource,
              }}
            />
          </>
        ),
      },
      {
        tab: 'T-BOX日志记录',
        key: 'logging',
        render: () => (
          <div className={style.tbox}>
            <SearchTable
              tableProps={{
                rowKey: 'sid',
                scroll: { x: 'max-content' },
                columns: TBoxColumns,
                onSource: this.getTBoxList,
              }}
              searchProps={{
                searchItems,
                customStyle: customStyle,
                resetItem: this.resetLogType,
                onRef: e => {
                  this.searchRef = e.current;
                },
              }}
            >
          {isAuth ? (
           <div>
            日志类型：
            <Select
            value={this.state.logType}
            style={{width: '250px'}}
            allowClear={true}
            placeholder="请选择日志类型"
            getPopupContainer={(triggerNode) => triggerNode.parentNode}    
            onChange={this.onTypeChange}
            options={logTypeMask}
            >
            </Select>
             <Button
                type="primary"
                size="small"
                className="btn-type"
                onClick={this.getStatusFn}
                loading={statusNum > 0}
              >
                {statusNum > 0 ? `${statusNum}s 后可再次获取` : '获取日志'}
              </Button>
              </div>
            ) :
            (
              <Button
                type="primary"
                size="small"
                className="btn-log"
                onClick={this.getStatusFn}
                loading={statusNum > 0}
              >
                {statusNum > 0 ? `${statusNum}s 后可再次获取` : '获取日志'}
              </Button>

            )}
            </SearchTable>
          </div>
        ),
      },
    ];
    return (
      <>
        <Card bordered={false} loading={loading}>
          <Descriptions bordered size="small" style={{ overflow: 'hidden' }}>
            <Descriptions.Item label="TBOX编号">{data.deviceId}</Descriptions.Item>
            <Descriptions.Item label="设备名称">{data.deviceName}</Descriptions.Item>
            <Descriptions.Item label="设备状态">
              {data.deviceStatus
                ? getDicByKey(context.dicData, 'deviceStatus', data.deviceStatus.toString())
                : ''}
            </Descriptions.Item>
            <Descriptions.Item label="硬件版本号">{data.versionHardware}</Descriptions.Item>
            <Descriptions.Item label="入库时间">{data.createDate}</Descriptions.Item>
            <Descriptions.Item label="软件版本号">{data.versionSoftware}</Descriptions.Item>
            <Descriptions.Item label="批次号">{data.batchNo}</Descriptions.Item>
            <Descriptions.Item label="IMEI">{data.imei}</Descriptions.Item>
            <Descriptions.Item label="WIFI账号">{data.ssid}</Descriptions.Item>
            <Descriptions.Item label="WIFI密码">{data.pin}</Descriptions.Item>
            <Descriptions.Item label="定位蓝牙ID">{data.locBluetoothIds}</Descriptions.Item>
            <Descriptions.Item label="动态秘钥">{data.dynamicSecretkey}</Descriptions.Item>
            <Descriptions.Item label="蓝牙识别码">{data.deviceSkey}</Descriptions.Item>
            <Descriptions.Item label="蓝牙MAC地址">{data.bluetoothMac}</Descriptions.Item>
            <Descriptions.Item label="蓝牙ID">{data.bluetoothId}</Descriptions.Item>
            <Descriptions.Item label="蓝牙名称">{data.bluetoothName}</Descriptions.Item>
            <Descriptions.Item label="eolDate">{data.eolDate}</Descriptions.Item>
            <Descriptions.Item label="aesKey">{data.aesKey}</Descriptions.Item>
            <Descriptions.Item label="atbType">{data.atbType}</Descriptions.Item>
            <Descriptions.Item label="productReference">
              {data.productReference
                ? getDicByKey(context.dicData, 'productReference', data.productReference)
                : '高级T'}
            </Descriptions.Item>
            <Descriptions.Item label="apnFlag">
              {data.apnFlag ? getDicByKey(context.dicData, 'apnFlag', data.apnFlag) : ''}
            </Descriptions.Item>
            <Descriptions.Item label="一体机编号">{data.atbSn}</Descriptions.Item>
          </Descriptions>
        </Card>
        {/* title="换件历史记录" */}
        <Card
          tabList={tabList}
          onTabChange={current => {
            this.setState({ current });
          }}
          bordered={false}
        >
          {tabList.find(e => e.key === current)?.render()}
        </Card>
      </>
    );
  }
}
